// 2025.10.06 15:12:12 星期一 晴 无事

import { Response } from 'express';
import { req_info_user_login } from '../../req_res/cla_req_info_user_login';
import { get_db_user_account } from '../../../create_acount/Func/get_db';
import { res_send_login_cur_account_no_matched } from '../../req_res/cla_res_send_login_cur_account_no_matched';
import {
  mdb_info_user_account,
  user_account_prop_Identity,
  user_account_prop_phone,
  user_account_prop_self_account,
} from '../../../../Func/sign_info_user_account/Classes/cla_mdb_info_user_account';
import fs from 'fs-extra';
import { get_file_path_cur_user_id } from '../../../../Func/Set_file/Func/get_file_path_cur_user';
import { prop_user_passworld } from '../../../create_acount/Classes/cla_req_info_create_account';
import { res_send_login_access } from '../../req_res/cla_res_send_login_access';
import { res_send_login_cur_passworld_no_matched } from '../../req_res/cla_res_send_login_cur_passworld_no_matched';

// 这个是 检测 用户 账户 及 密码 是否 匹配

export async function check_cur_user_account_passworld(
  cur_info: req_info_user_login,
  res: Response
) {
  let cur_user_queue = await check_cur_account_is_create(cur_info.account, res);

  if (cur_user_queue === false) {
    return false;
  }

  let passworld_is_matched = await check_cur_user_passworld(
    cur_user_queue,
    cur_info.passworld,
    res
  );

  return passworld_is_matched;
}

/**
 * 检测 账号 是否存在
 *
 * 返回 账号 的 全局 id
 */
async function check_cur_account_is_create(
  account: req_info_user_login['account'],
  res: Response
) {
  let db_user_account = get_db_user_account();

  let search_account_info = await db_user_account
    .find({
      $or: [
        { [user_account_prop_phone]: account },
        { [user_account_prop_Identity]: account },
        { [user_account_prop_self_account]: account },
      ],
    })
    .toArray();

  if (search_account_info.length == 1) {
    let cur_user_info: mdb_info_user_account = search_account_info[0] as any;
    return cur_user_info.id;
  }

  let res_send = new res_send_login_cur_account_no_matched();

  res.send(res_send);

  return false;
}

/**
 * 检测 当前 用户 的 密码 是否 匹配 成功
 */
async function check_cur_user_passworld(
  cur_user_id: string,
  passworld: req_info_user_login['passworld'],
  res: Response
) {
  let cur_file_json = await fs.readJson(get_file_path_cur_user_id(cur_user_id));

  if (cur_file_json[prop_user_passworld] == passworld) {
    let res_send = new res_send_login_access();

    res.send(res_send);
    return true;
  }

  let res_send = new res_send_login_cur_passworld_no_matched();

  res.send(res_send);

  return false;
}
